package web.testBIO;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Random;

public class Server {

	private static String ip = "127.0.0.1";

	private static int port = 8888;

	public static void main(String[] args) {

		try {
			InetSocketAddress address = new InetSocketAddress(ip, port);
			ServerSocket serverSocket = new ServerSocket();
			serverSocket.bind(address);
			System.out.println("服务端已经启动");
			while(true) {
				Socket accept = serverSocket.accept();
				try {
					BufferedReader in = new BufferedReader(new InputStreamReader(accept.getInputStream()));
					PrintWriter out = new PrintWriter(accept.getOutputStream(), true);
					String body = null;
					while ((body = in.readLine()) != null) {
						System.out.println("Server :" + body);
					}
					accept.shutdownInput();
					out.println("服务器端回送响的应数据." + new Random().nextInt());
					accept.shutdownOutput();
				} catch (Exception e) {
					e.printStackTrace();
					
				}finally {
					accept.close();
				}
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

}

class HandlerClient implements Runnable {

	private ServerSocket serverSocket;

	public HandlerClient(ServerSocket serverSocket) {
		super();
		this.serverSocket = serverSocket;
	}

	@Override
	public void run() {
		while (true) {

			try {
				Socket accept = serverSocket.accept();
				System.out.println("接收了请求");
				new Thread(new HandlerClientRequest(accept, serverSocket)).start();
			} catch (Exception e) {
				e.printStackTrace();
			}

		}

	}

}

class HandlerClientRequest implements Runnable {

	private Socket socket;

	private ServerSocket serverSocket;

	public HandlerClientRequest(Socket socket, ServerSocket serverSocket) {
		super();
		this.socket = socket;
		this.serverSocket = serverSocket;
	}

	@Override
	public void run() {

		try {
			BufferedReader in = new BufferedReader(new InputStreamReader(this.socket.getInputStream()));
			PrintWriter	out = new PrintWriter(this.socket.getOutputStream(), true);
			String body = null;
			while ((body = in.readLine())!=null) {
				System.out.println("Server :" + body);
			}
			socket.shutdownInput();
			out.println("服务器端回送响的应数据."+new Random().nextInt());
			socket.shutdownOutput();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {

		}

	}

}
